<script setup>
import { ref, reactive } from "vue";
import { getHelpList, addHelp, delHelp, editHelp } from "@/api/helpcenter";

const tableData = ref([]);
const formRef = ref();
const rules = reactive({
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  detail: [{ required: true, message: "请输入详情", trigger: "blur" }],
});
const dialogConfig = reactive({
  show: false,
  title: "添加",
  type: 'add',
});
const formData = reactive({
  id: "",
  title: "",
  detail: "",
  loading: false,
});
getList()
async function getList() {
  const res = await getHelpList();
  tableData.value = res.data;
  console.log(res.data)
}
function addFn() {
  dialogConfig.show = true;
  dialogConfig.title = "添加";
  dialogConfig.type = "add"
  formData.title = ""
  formData.detail = ""
  formData.id = ""
}
function editFn(data) {
  dialogConfig.show = true;
  dialogConfig.title = "编辑";
  dialogConfig.type = "edit"
  formData.title = data.title
  formData.detail = data.detail
  formData.id = data.id
}

async function submitForm(formEl) {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      formData.loading = true;
      const fn = dialogConfig.type == "add" ? addHelp : editHelp
      const res = await fn(formData)
      formData.loading = false;
      dialogConfig.show = false
      getList()
    }
  });
}
async function delFn(id) {
  formData.loading = true;
  const res = await delHelp({ id })
  formData.loading = false;
  getList()
}
</script>

<template>
  <div class="container">
    <p class="title">帮助中心</p>
    <div class="box">
      <p class="tool">
        <el-button type="primary" @click="addFn()">添加</el-button>
      </p>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="detail" label="详情" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button :loading="formData.loading" type="primary" @click="editFn(scope.row)">编辑</el-button>
            <el-button :loading="formData.loading" type="warning" @click="delFn(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <el-dialog v-model="dialogConfig.show" :title="dialogConfig.title">
    <el-form ref="formRef" :model="formData" :rules="rules" status-icon>
      <el-form-item prop="title" label="标题">
        <el-input v-model="formData.title"></el-input>
      </el-form-item>
      <el-form-item prop="detail" label="详情">
        <el-input v-model="formData.detail" type="textarea" :autosize="{ minRows: 4, maxRows: 8 }"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button :loading="formData.loading" type="primary" @click="submitForm(formRef)">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>